<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
        <div id="title">
            <!-- 给每个按钮设定属性 -->
            <button data-url="/center">个人中心</button>
            <button data-url="/news">新闻</button>
            <button data-url="/music">音乐</button>
        </div>
        <div id="views">

        </div>
        <script>
            //获取dom
            const obtns = document.querySelectorAll("#title button")
            const oView = document.querySelector("#views")
            //创建路由表
            const routes=[
                {path:"/center",countent:"个人中心"},
                {path:"/news",countent:"新闻"},
                {path:"/music",countent:"音乐"}
            ]
            //遍历所有obtn 绑定事件
            //history路由需要后端支持
            for (var i = 0; i < obtns.length; i++) {
                    obtns[i].onclick = function () {
                        //绑定hisstory路由
                        history.pushState(null, null, this.dataset.url)
                        //遍历routes 
                        routes.forEach((item) => {
                            if (item.path === this.dataset.url) {
                                oView.textContent = item.countent
                            }
                        })
                    }
            }
              //onpopstate 当通过历史记录改变浏览器的地址的时候 就会触发
              window.onpopstate =function(){
                //可以通过location.pathname拿到改变的histroy
                // console.log(location.pathname);
                routes.forEach((item) => {
                            if (item.path === location.pathname) {
                                oView.textContent = item.countent
                            }
                        })
              }

        </script>
</body>
</html>